package com.wocai.jrt.orgadmin.asset.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vteba.common.exception.ServiceException;
import com.vteba.service.generic.impl.MyBatisServiceImpl;
import com.vteba.tx.jdbc.mybatis.spi.BaseDao;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.approve.model.ApproveRoleGroup;
import com.wocai.jrt.orgadmin.approve.model.ApproveRoleGroupMember;
import com.wocai.jrt.orgadmin.approve.model.ApproveRoleGroupMemberBean;
import com.wocai.jrt.orgadmin.approve.service.spi.ApproveRoleGroupMemberService;
import com.wocai.jrt.orgadmin.approve.service.spi.ApproveRoleGroupService;
import com.wocai.jrt.orgadmin.asset.bean.AssetAllocationBean;
import com.wocai.jrt.orgadmin.asset.bean.AssetAllocationHistoryResBean;
import com.wocai.jrt.orgadmin.asset.bean.AssetAllocationReqBean;
import com.wocai.jrt.orgadmin.asset.bean.AssetAllocationResBean;
import com.wocai.jrt.orgadmin.asset.dao.AssetAllocationDao;
import com.wocai.jrt.orgadmin.asset.model.AssetAllocation;
import com.wocai.jrt.orgadmin.asset.service.spi.AssetAllocationService;
import com.wocai.jrt.orgadmin.flow.model.Flow;
import com.wocai.jrt.orgadmin.flow.model.FlowInstance;
import com.wocai.jrt.orgadmin.flow.model.FlowLog;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowInstanceService;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowLogService;
import com.wocai.jrt.orgadmin.flow.service.spi.FlowService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 资产配置相关的service业务实现。
 * 
 * @author yinlei
 * @date 2016-3-17 17:47:55
 */
@Named
public class AssetAllocationServiceImpl extends
		MyBatisServiceImpl<AssetAllocation, AssetAllocationBean, String>
		implements AssetAllocationService {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(AssetAllocationServiceImpl.class);
	// 添加了方法后，记得改为private
	private AssetAllocationDao assetAllocationDao;
	@Inject
	private FlowService flowServiceImpl;
	@Inject
	private FlowInstanceService flowInstanceServiceImpl;
	@Inject
	private FlowLogService flowLogServiceImpl;
	@Inject
	private ApproveRoleGroupService approveRoleGroupServiceImpl;
	@Inject
	private ApproveRoleGroupMemberService approveRoleGroupMemberServiceImpl;

	@Override
	@Inject
	public void setBaseDao(
			BaseDao<AssetAllocation, AssetAllocationBean, String> assetAllocationDao) {
		this.baseDao = assetAllocationDao;
		this.assetAllocationDao = (AssetAllocationDao) assetAllocationDao;
	}

	@Override
	public int countAssetAllocationResBeanList(AssetAllocationReqBean model) {
		return assetAllocationDao.countAssetAllocationResBeanList(model);
	}

	@Override
	public List<AssetAllocationResBean> getAssetAllocationResBeanList(
			AssetAllocationReqBean model) {
		return assetAllocationDao.getAssetAllocationResBeanList(model);
	}

	@Override
	public JsonBean saveAssetAllocation(AssetAllocation model) {
		JsonBean jsonBean = new JsonBean();
		try {
			// 插入审批流程 目前只设全局
			Flow flow = new Flow();
			flow.setType(1);
			flow.setState(true);
			flow.setFlag(true);
			flow = flowServiceImpl.unique(flow);
			if (null == flow) {
				jsonBean.setCode(0);
				jsonBean.setMessage("全局流程未定义");
				return jsonBean;
			}

			String assetAllocationId = ObjectId.get().toString();
			model.setFlowId(flow.getId());
			model.setId(assetAllocationId);
			model.setState(1);
			model.setOrgId(UserUtils.getOrgId());
			int result = assetAllocationDao.save(model);
			// 流程实例添加
			FlowInstance flowInstance = new FlowInstance();
			flowInstance.setId(ObjectId.get().toString());
			flowInstance.setEventId(assetAllocationId);
			flowInstance.setFlowId(flow.getId());
			flowInstance.setNowStep(1);
			int resultFlow = flowInstanceServiceImpl.save(flowInstance);
			// 流程日志添加
			FlowLog flowLog = new FlowLog();
			flowLog.setId(ObjectId.get().toString());
			flowLog.setCreateTime(new Date());
			flowLog.setEmployeeId(UserUtils.getUserId());
			flowLog.setEmployeeName(UserUtils.getUser().getName());
			flowLog.setStepName("资产配置添加");
			flowLog.setOrgId(UserUtils.getOrgId());
			flowLog.setEventId(assetAllocationId);
			int resultFlowLog = flowLogServiceImpl.save(flowLog);

			if (1 == result && 1 == resultFlow && 1 == resultFlowLog) {
				jsonBean.setCode(1);
				jsonBean.setMessage("success");
				jsonBean.setData(model);
			}
		} catch (Exception e) {
			throw new ServiceException("资产配置添加错误:" + e.getMessage());
		}
		return jsonBean;
	}

	@Override
	public JsonBean submitAudit(String id) {
		JsonBean jsonBean = new JsonBean();
		try {
			AssetAllocation assetAllocation = assetAllocationDao.get(id);
			if (null == assetAllocation) {
				jsonBean.setCode(0);
				jsonBean.setMessage("id错误");
				return jsonBean;
			}

			// 设为审核中
			assetAllocation.setState(2);
			assetAllocation.setTime(new Date());
			assetAllocation.setEmployeeId(UserUtils.getUserId());

			// 设项目配置总金额
			assetAllocation.setAmount(assetAllocationDao
					.sumAllocationDetailAmout(id));
			int result = assetAllocationDao.updateById(assetAllocation);

			// 流程走到第二步 设为资产委员会审批中
			FlowInstance flowInstance = new FlowInstance();
			flowInstance.setEventId(id);
			flowInstance = flowInstanceServiceImpl.unique(flowInstance);
			if (null == flowInstance) {
				jsonBean.setCode(0);
				jsonBean.setMessage("流程实例未初始化");
				return jsonBean;
			}
			flowInstance.setNowStep(2);

			// 流程日志添加
			FlowLog flowLog = new FlowLog();
			flowLog.setId(ObjectId.get().toString());
			flowLog.setCreateTime(new Date());
			flowLog.setEmployeeId(UserUtils.getUserId());
			flowLog.setEmployeeName(UserUtils.getUser().getName());
			flowLog.setStepName("资产配置提交审批");
			flowLog.setOrgId(UserUtils.getOrgId());
			flowLog.setEventId(id);
			int resultFlowLog = flowLogServiceImpl.save(flowLog);

			int resultFlow = flowInstanceServiceImpl.updateById(flowInstance);
			if (1 == result && 1 == resultFlow && 1 == resultFlowLog) {
				jsonBean.setCode(1);
				jsonBean.setMessage("提交审批成功");
			}
		} catch (Exception e) {
			throw new ServiceException(e.getMessage());
		}
		return jsonBean;
	}

	@Override
	public List<AssetAllocationHistoryResBean> getAssetAllocationHistory(
			String productId) {
		return assetAllocationDao.getAssetAllocationHistory(productId);
	}

	@Override
	public int countAssetAllocationHistory(String productId) {
		return assetAllocationDao.countAssetAllocationHistory(productId);
	}

	@Override
	public List<AssetAllocationBean> queryAssetAllocationList(
			AssetAllocationReqBean model) {
		return assetAllocationDao.queryAssetAllocationList(model);
	}

	@Override
	public int countAssetAllocationBy(AssetAllocationReqBean model) {
		return assetAllocationDao.countAssetAllocationBy(model);
	}

	@Override
	public JsonBean voteHandle(FlowLog flowLog) {
		JsonBean jsonBean = new JsonBean();
		try {
			// 查询事项id对应的资产配置
			AssetAllocation allocation = assetAllocationDao.get(flowLog
					.getEventId());
			if (null == allocation) {
				jsonBean.setCode(0);
				jsonBean.setMessage("事项id为非对应资产配置id");
				return jsonBean;
			}

			// 查询初审委员会成员的个数 不包括负责人
			List<ApproveRoleGroupMember> aGroupMembers = new ArrayList<ApproveRoleGroupMember>();
			ApproveRoleGroup approveRoleGroup = new ApproveRoleGroup();
			// 1投资部，2尽调小组，3项目初审委员会，4项目决策委员会，5法律合规部，6项目最终审批人，7资金运用决策委员会，8资金运用最终审批人
			approveRoleGroup.setType(7);
			approveRoleGroup = approveRoleGroupServiceImpl
					.unique(approveRoleGroup);
			if (null == approveRoleGroup) {
				jsonBean.setCode(0);
				jsonBean.setMessage("资金运用决策委员会未添加");
				LOGGER.error("资金运用决策委员会未添加");
				return jsonBean;
			}
			ApproveRoleGroupMemberBean approveRoleGroupMember = new ApproveRoleGroupMemberBean();
			approveRoleGroupMember.createCriteria()
					.andApproveRoleGroupIdEqualTo(approveRoleGroup.getId())
					.andEmployeeIdNotEqualTo(approveRoleGroup.getEmployeeId());
			aGroupMembers = approveRoleGroupMemberServiceImpl
					.queryForList(approveRoleGroupMember);
			if (null == aGroupMembers) {
				jsonBean.setCode(0);
				jsonBean.setMessage("资金运用决策委员会成员未添加");
				LOGGER.error("资金运用决策委员会成员未添加");
				return jsonBean;
			}
			// 检查当前操作人员是否属于委员会中
			String currentEmployeeId = UserUtils.getUserId();
			Boolean isGroupMember = false;
			for (ApproveRoleGroupMember member : aGroupMembers) {
				if (member.getEmployeeId().equals(currentEmployeeId)) {
					isGroupMember = true;
					break;
				}
			}
			if (!isGroupMember) {// 非成员内
				jsonBean.setCode(0);
				jsonBean.setMessage("您非资金运用决策委员会成员");
				LOGGER.error("当前请求来之于非资金运用决策委员会成员");
				return jsonBean;
			}

			// 查询是否已经表决  add 事项ID
			FlowLog flow = new FlowLog();
			flow.setEventId(flowLog.getEventId());
			flow.setStepName("资产运用决策委员会成员审批");
			flow.setEmployeeId(currentEmployeeId);
			flow = flowLogServiceImpl.unique(flow);
			if (null != flow) {
				jsonBean.setCode(0);
				jsonBean.setMessage("您已经表决过了");
				LOGGER.error("当前请求用户已经表决过。");
				return jsonBean;
			}

			// 插入流程日志
			flowLog.setCreateTime(new Date());
			flowLog.setEmployeeId(currentEmployeeId);
			flowLog.setEmployeeName(UserUtils.getUser().getName());
			flowLog.setId(ObjectId.get().toString());
			flowLog.setOrgId(UserUtils.getOrgId());
			flowLog.setStepName("资产运用决策委员会成员审批");
			int result = flowLogServiceImpl.save(flowLog);
			if (1 != result) {
				jsonBean.setCode(0);
				jsonBean.setMessage("更新至流程日志中失败");
				LOGGER.error("更新至流程日志中失败");
				return jsonBean;
			}

			//判断成员是否全部表决
			Boolean isFinishVote = true;
			for (ApproveRoleGroupMember member : aGroupMembers) {
				
				//判断 member 是否表决
				FlowLog flow2 = new FlowLog();
				flow2.setEventId(flowLog.getEventId());
				flow2.setStepName("资产运用决策委员会成员审批");
				flow2.setEmployeeId(member.getEmployeeId());
				flow2 = flowLogServiceImpl.unique(flow2);
				if (null == flow2) {
					LOGGER.error("当前请求用户" + member.getEmployeeId() + "未表决。");
					isFinishVote = false;
					
					//直接停止
					break;
				}
			}
			
			//没有用户未表决，即表决完成，更新流程实例的状态 更新资产配置状态
			if (isFinishVote) {
				
				// 流程走到第三步 设为资产运用决策委员会负责人审批
				FlowInstance flowInstance = new FlowInstance();
				flowInstance.setEventId(flowLog.getEventId());
				flowInstance = flowInstanceServiceImpl.unique(flowInstance);
				if (null == flowInstance) {
					jsonBean.setCode(0);
					jsonBean.setMessage("流程实例未初始化");
					return jsonBean;
				}
				
				//NowStep 1-项目信息录入  2-资产运用决策委员会审批  3-资产运用决策委员会负责人审批  4-资金运用最终审批人审批 5-资产配置信息录入
				flowInstance.setNowStep(3);
				int resultFlow = flowInstanceServiceImpl.updateById(flowInstance);
				if (1 != resultFlow) {
					jsonBean.setCode(0);
					jsonBean.setMessage("流程实例更新失败");
					LOGGER.error("flowLog.getEventId() = " + flowLog.getEventId() + "流程实例更新失败");
					return jsonBean;				
				}
				
				//个人表决不需要更新，待负责人表决完成更新
				//更新资产配置状态
				/*AssetAllocation assetAllocation = assetAllocationDao.get(flowInstance.getEventId());
				if (null == assetAllocation) {
					jsonBean.setCode(0);
					jsonBean.setMessage("id错误");
					return jsonBean;
				}

				// 设为审批中
				//状态(1待审批，2审批中，3终审中，4过终审，5已投资)
				assetAllocation.setState(3);
				int stateResult = assetAllocationDao.updateById(assetAllocation);
				if(1 != stateResult){
					jsonBean.setCode(0);
					jsonBean.setMessage("资产配置状态更新失败");
					LOGGER.error("assetAllocation.getId() = " + assetAllocation.getId() + "资产配置状态更新失败");
					return jsonBean;
				}*/
			}
			
			//已经成功
			jsonBean.setCode(1);
			jsonBean.setMessage("success");
		} catch (Exception e) {
			throw new ServiceException("个人表决失败" + e.getMessage());
		}
		return jsonBean;
	}

	@Override
	public JsonBean approveHandle(FlowLog flowLog) {
		JsonBean jsonBean = new JsonBean();
		try {
			// 查询事项id对应的资产配置
			AssetAllocation allocation = assetAllocationDao.get(flowLog
					.getEventId());
			if (null == allocation) {
				jsonBean.setCode(0);
				jsonBean.setMessage("事项id为非对应资产配置id");
				return jsonBean;
			}

			//资金运用决策委员会
			ApproveRoleGroup approveRoleGroup = new ApproveRoleGroup();
			
			// 1投资部，2尽调小组，3项目初审委员会，4项目决策委员会，5法律合规部，6项目最终审批人，7资金运用决策委员会，8资金运用最终审批人
			approveRoleGroup.setType(7);
			approveRoleGroup = approveRoleGroupServiceImpl
					.unique(approveRoleGroup);
			if (null == approveRoleGroup) {
				jsonBean.setCode(0);
				jsonBean.setMessage("资金运用决策委员会未添加");
				LOGGER.error("资金运用决策委员会未添加");
				return jsonBean;
			}
			
			//负责人为空
			if(StringUtils.isBlank(approveRoleGroup.getEmployeeId())){
				jsonBean.setCode(0);
				jsonBean.setMessage("资金运用决策委员会负责人未添加");
				LOGGER.error("资金运用决策委员会负责人未添加");
				return jsonBean;
			}

			// 检查当前操作人员是否属于委员会中的负责人
			String userID = UserUtils.getUserId();
			if(! userID.equals(approveRoleGroup.getEmployeeId())){
				jsonBean.setCode(0);
				jsonBean.setMessage("您非资金运用决策委员会负责人");
				LOGGER.error("当前请求来之于非资金运用决策委员会负责人");
				return jsonBean;
			}

			// 查询是否已经表决
			FlowLog flow = new FlowLog();
			flow.setEventId(flowLog.getEventId());
			flow.setStepName("资产运用决策委员会负责人审批");
			flow.setEmployeeId(userID);
			flow = flowLogServiceImpl.unique(flow);
			if (null != flow) {
				jsonBean.setCode(0);
				jsonBean.setMessage("您已经表决过了");
				LOGGER.error("当前请求用户已经表决过。");
				return jsonBean;
			}

			// 插入流程日志
			flowLog.setCreateTime(new Date());
			flowLog.setEmployeeId(userID);
			flowLog.setEmployeeName(UserUtils.getUser().getName());
			flowLog.setId(ObjectId.get().toString());
			flowLog.setOrgId(UserUtils.getOrgId());
			flowLog.setStepName("资产运用决策委员会负责人审批");
			int result = flowLogServiceImpl.save(flowLog);
			if (1 != result) {
				jsonBean.setCode(0);
				jsonBean.setMessage("更新至流程日志中失败");
				LOGGER.error("更新至流程日志中失败");
				return jsonBean;
			}

			// 流程走到第三步 资产运用决策委员会负责人审批
			FlowInstance flowInstance = new FlowInstance();
			flowInstance.setEventId(flowLog.getEventId());
			flowInstance = flowInstanceServiceImpl.unique(flowInstance);
			if (null == flowInstance) {
				jsonBean.setCode(0);
				jsonBean.setMessage("流程实例未初始化");
				return jsonBean;
			}
			
			//NowStep 1-项目信息录入  2-资产运用决策委员会审批  3-资产运用决策委员会负责人审批  4-资金运用最终审批人审批 5-资产配置信息录入
			flowInstance.setNowStep(4);
			int resultFlow = flowInstanceServiceImpl.updateById(flowInstance);
			if (1 != resultFlow) {
				jsonBean.setCode(0);
				jsonBean.setMessage("流程实例更新失败");
				LOGGER.error("flowLog.getEventId() = " + flowLog.getEventId() + "流程实例更新失败");
				return jsonBean;				
			}
			
			//更新资产配置状态
			AssetAllocation assetAllocation = assetAllocationDao.get(flowInstance.getEventId());
			if (null == assetAllocation) {
				jsonBean.setCode(0);
				jsonBean.setMessage("id错误");
				return jsonBean;
			}

			// 设为终审中
			//状态(1待审批，2审批中，3终审中，4过终审，5已投资)
			assetAllocation.setState(3);
			int stateResult = assetAllocationDao.updateById(assetAllocation);
			if(1 != stateResult){
				jsonBean.setCode(0);
				jsonBean.setMessage("资产配置状态更新失败");
				LOGGER.error("assetAllocation.getId() = " + assetAllocation.getId() + "资产配置状态更新失败");
				return jsonBean;
			}
		
			jsonBean.setCode(1);
			jsonBean.setMessage("success");
		} catch (Exception e) {
			throw new ServiceException("资产运用决策委员会负责人审批失败" + e.getMessage());
		}
		return jsonBean;
	}

	@Override
	public JsonBean approveFinalHandle(FlowLog flowLog) {
		JsonBean jsonBean = new JsonBean();
		try {
			// 查询事项id对应的资产配置
			AssetAllocation allocation = assetAllocationDao.get(flowLog
					.getEventId());
			if (null == allocation) {
				jsonBean.setCode(0);
				jsonBean.setMessage("事项id为非对应资产配置id");
				return jsonBean;
			}
			
			// 检查当前操作人员是否属于委员会中的负责人
			String userID = UserUtils.getUserId();

			// 查询是否已经表决
			FlowLog flow = new FlowLog();
			flow.setEventId(flowLog.getEventId());
			flow.setStepName("资金运用最终审批人审批");
			flow.setEmployeeId(userID);
			flow = flowLogServiceImpl.unique(flow);
			if (null != flow) {
				jsonBean.setCode(0);
				jsonBean.setMessage("您已经表决过了");
				LOGGER.error("当前请求用户已经表决过。");
				return jsonBean;
			}

			// 插入流程日志
			flowLog.setCreateTime(new Date());
			flowLog.setEmployeeId(userID);
			flowLog.setEmployeeName(UserUtils.getUser().getName());
			flowLog.setId(ObjectId.get().toString());
			flowLog.setOrgId(UserUtils.getOrgId());
			flowLog.setStepName("资金运用最终审批人审批");
			int result = flowLogServiceImpl.save(flowLog);
			if (1 != result) {
				jsonBean.setCode(0);
				jsonBean.setMessage("更新至流程日志中失败");
				LOGGER.error("更新至流程日志中失败");
				return jsonBean;
			}

			// 流程走到第四步 设为 资金运用最终审批人审批
			FlowInstance flowInstance = new FlowInstance();
			flowInstance.setEventId(flowLog.getEventId());
			flowInstance = flowInstanceServiceImpl.unique(flowInstance);
			if (null == flowInstance) {
				jsonBean.setCode(0);
				jsonBean.setMessage("流程实例未初始化");
				return jsonBean;
			}
			
			//NowStep 1-项目信息录入  2-资产运用决策委员会审批  3-资产运用决策委员会负责人审批  4-资金运用最终审批人审批 5-资产配置信息录入
			flowInstance.setNowStep(4);
			int resultFlow = flowInstanceServiceImpl.updateById(flowInstance);
			if (1 != resultFlow) {
				jsonBean.setCode(0);
				jsonBean.setMessage("流程实例更新失败");
				LOGGER.error("flowLog.getEventId() = " + flowLog.getEventId() + "流程实例更新失败");
				return jsonBean;				
			}
			
			//更新资产配置状态
			AssetAllocation assetAllocation = assetAllocationDao.get(flowInstance.getEventId());
			if (null == assetAllocation) {
				jsonBean.setCode(0);
				jsonBean.setMessage("id错误");
				return jsonBean;
			}

			// 设为过终审
			//状态(1待审批，2审批中，3终审中，4过终审，5已投资)
			assetAllocation.setState(4);
			int stateResult = assetAllocationDao.updateById(assetAllocation);
			if(1 != stateResult){
				jsonBean.setCode(0);
				jsonBean.setMessage("资产配置状态更新失败");
				LOGGER.error("assetAllocation.getId() = " + assetAllocation.getId() + "资产配置状态更新失败");
				return jsonBean;
			}
		
			jsonBean.setCode(1);
			jsonBean.setMessage("success");
		} catch (Exception e) {
			throw new ServiceException("资产运用决策委员会负责人审批失败" + e.getMessage());
		}
		return jsonBean;
	}
	
	
}
